package com.keymozy.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.keymozy.mapper.*;
import com.keymozy.pojo.*;
import com.keymozy.pojo.dto.DtoDept;
import com.keymozy.service.MChildService;
import com.keymozy.util.GetTimeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.CrossOrigin;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Slf4j
@Service
public class IMChildService implements MChildService {
    @Autowired
    private MChildMapper mChildMapper;
    @Autowired
    private ModelMapper modelMapper;
    @Autowired
    private StoreMapper storeMapper;
    @Autowired
    private ZoneMapper zoneMapper;
    @Autowired
    private BorrowMapper borrowMapper;

    @Override
    public Map<String,Object> getList(int currentPage, int pageSize, Integer state, Model model) {
        Page<Model> p = new Page<>(currentPage,pageSize);
        HashMap<String,Object> data = new HashMap<>();
            LambdaQueryWrapper<Model> lqw = new LambdaQueryWrapper<>();
            if (model!=null){
                log.info("进入了判断");
                lqw.like(model.getMname()!=null&&!"".equals(model.getMname()),Model::getMname,model.getMname());
                lqw.eq(model.getZid()!=null,Model::getZid,model.getZid());
                lqw.eq(model.getId()!=null,Model::getId,model.getId());
            }
        List<Model> modelList = setMchilds(modelMapper.selectList(lqw), state);
        modelList=modelList.stream().skip((currentPage-1)*2).limit(2).collect(Collectors.toList());
        data.put("total",1000);
        data.put("data",modelList);
        return data;
    }

    /**
     *借用模具
     * @param mid
     * @param sid
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean borrow(Integer mid, Integer sid) {
        MChild mc = mChildMapper.selectById(mid);
        if (mc.getState() == null){
            return false;
        }
        log.info("正在判断状态~~");
        switch (mc.getState()){
            case 0:
                break;
            default:
                return false;
        }
        mc.setState(2);
        Borrow borrow = new Borrow();
        borrow.setMid(mid);
        borrow.setSid(sid);
        borrow.setBtime(GetTimeUtil.getTimeOfSeconds());
        mChildMapper.updateById(mc);
        borrowMapper.insert(borrow);
        return true;
    }

    /**
     *获得已借用的模具
     * @param sid
     * @return
     */
    @Override
    public List<Borrow> getBorrow(Integer sid) {
        LambdaQueryWrapper<Borrow> lqw = new LambdaQueryWrapper<>();
        lqw.eq(Borrow::getSid,sid);
        lqw.isNull(Borrow::getRtime);
        List<Borrow> borrows = borrowMapper.selectList(lqw);
        if (borrows==null){
            return null;
        }
        setBorrowModel(borrows);
        log.info("borrow:"+borrows);
        return borrows;
    }
    @Transactional
    @Override
    public boolean toReturn(Borrow borrow) {
        log.info("borrow:"+borrow);
        if (borrow == null){
            return false;
        }
        LambdaQueryWrapper<MChild> lqw = new LambdaQueryWrapper<>();
        lqw.eq(MChild::getId,borrow.getMid());
        MChild child = mChildMapper.selectOne(lqw);
        log.info("child:"+child);
        child.setState(0);
        mChildMapper.updateById(child);
        borrow.setRtime(GetTimeUtil.getTimeOfSeconds());
        return borrowMapper.updateById(borrow)==1;
    }

    /**
     * 设置模具状态
     * @param mid
     * @param flag
     * @return
     */
    @Override
    public boolean setState(Integer mid, Integer flag) {
        if (mid == null || flag == null){
            return false;
        }
        MChild mChild = mChildMapper.selectById(mid);
        mChild.setState(flag);
        int state = mChildMapper.updateById(mChild);
        return state==1;
    }

    @Override
    public List<Model> getMaintain(Long time) {
        return null;
    }

    @Override
    public List<DtoDept> statistics() {
        LambdaQueryWrapper<MChild> fix = new LambdaQueryWrapper<MChild>().eq(MChild::getState, 0);
        LambdaQueryWrapper<MChild>  borrow = new LambdaQueryWrapper<MChild>().eq(MChild::getState, 2);
        Integer fixCount = mChildMapper.selectCount(fix);
        Integer borrowCount = mChildMapper.selectCount(borrow);
        ArrayList<DtoDept> statistics = new ArrayList<>();
        DtoDept dtoFix = new DtoDept();
        dtoFix.setName("保养维修中");
        dtoFix.setValue(fixCount);
        DtoDept dtoBorrow = new DtoDept();
        dtoBorrow.setName("租借中");
        dtoBorrow.setValue(borrowCount);
        statistics.add(dtoBorrow);
        statistics.add(dtoFix);
        return statistics;
    }

    private void setBorrowModel(List<Borrow> borrows){
        for (Borrow borrow : borrows) {
            MChild mc = mChildMapper.selectById(borrow.getMid());
            Model model = modelMapper.selectById(mc.getMid());
            borrow.setMChild(mc);
            Zone zone = zoneMapper.selectById(model.getZid());
            Store store = storeMapper.selectById(zone.getSid());
            model.setSzname(store.getSname()+"-"+zone.getSname());
            borrow.setModel(model);
        }
    }

    public List<Model> setMchilds(List<Model> models,Integer state){
        ArrayList<Model> arrModels = new ArrayList<>();
        for (Model model : models) {
            System.out.println(model);
            Zone zone = zoneMapper.selectById(model.getZid());
            Store store = storeMapper.selectById(zone.getSid());
            model.setSzname(store.getSname()+"-"+zone.getSname());
            if(state!=null){
                List<MChild> mChildren = mChildMapper
                        .selectList(new LambdaQueryWrapper<MChild>()
                                        .eq(MChild::getMid, model.getId())
                                        .eq(MChild::getState,state));
                if(mChildren!=null&&mChildren.size()>0){
                   arrModels.add(model);
               }
            }else {
                List<MChild> mChildren = mChildMapper
                        .selectList(new LambdaQueryWrapper<MChild>()
                                .eq(MChild::getMid, model.getId())
                                .eq(MChild::getState,0));
                if(mChildren!=null&&mChildren.size()>0){
                    arrModels.add(model);
                }
            }
        }
            return arrModels;
    }
}
